<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\MpMpj;
use addons\alioss\controller\Index as IndexOssModel;
use app\admin\model\MpJson;
use app\admin\model\MpLick;
use app\admin\model\MpMp;
use app\admin\model\MpType as MpTypeModer;
use app\admin\model\UserOrder;
use think\Db;
use think\Exception;

class MpType extends Api
{
	protected $noNeedLogin = ['getmpinfo'];

	public function _initialize(){
		$action = request()->action();
	
		if(!in_array($action,$this->noNeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}


    //获取名片详情
    public function getMpInfo(){
        $id = $this->request->request('id','');
        $token = $this->request->request('token','');
        if(!$id){
            $this->error('参数错误');
        }
        $info = MpTypeModer::where(['id'=>$id])->find();
        if(!$info){
            $this->error('参数错误');
        }
		$info['mp_json'] = MpJson::where(['mp_type_id'=>$info['id']])->order('id desc')->find();


		$module_json_id = explode(',,,,',$info['module_json_id']);
        $module_json_name = explode(',,,,',$info['module_json_name']);
        $module_json_type = explode(',,,,',$info['module_json_type']);
        $module_json_status = explode(',,,,',$info['module_json_status']);
        $module_json_zdy_title = explode(',,,,',$info['module_json_zdy_title']);
        $module_json_text = explode(',,,,',$info['module_json_text']);
        $module_json_text_json = explode(',,,,',$info['module_json_text_json']);
        
        $arr = [];
        for ($i = 0; $i < count($module_json_id); $i++) {
            $category1 = [];
            $category = [];
            $json = json_decode(htmlspecialchars_decode($module_json_text_json[$i]),true);
            if($module_json_type[$i] == 4){
               
                $category[] = ['name'=>'全部'];
                foreach ($json as $v) {
                    if (!empty($v['category']) && !in_array($v['category'], $category1)) {
                        $category[] = ['name'=>$v['category']];
                        $category1[] = $v['category'];
                    }
                }
            }

            $text = htmlspecialchars_decode($module_json_text[$i]);
            if(!(!$text || $text == 'undefined')){
                $arr[] = [
                    'id'=>$module_json_id[$i],
                    'name'=>$module_json_name[$i],
                    'type'=>$module_json_type[$i],
                    'status'=>$module_json_status[$i],
                    'zdy_title'=>$module_json_zdy_title[$i],
                    'text'=>$text,
                    'text_json'=>htmlspecialchars_decode($module_json_text_json[$i]),
                    'json'=>$json,
                    'category'=>$category,
                    'category_arr'=>$json,
                ];
            }
        }
        
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        $info['module_json_arr'] = $arr;

        $arrList = [];
        $arr = [];
        for ($i=0; $i < 100; $i++) { 
            $url = 'https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com/img/wx'.rand(1,35).'.jpg';
            if(!in_array($url,$arr)){
                $arr[] = $url;
                $arrList[] = ['url'=>$url];
                if(count($arrList) >= 5){
                    break;
                }
            }
        }
        $info['like_num'] = $info['like_num'] +  MpLick::where(['type_id'=>$info['id']])->count();
        $info['mp_lick'] = -1;
        if($token){
            $user = User::where(array('token'=>$token))->find();
            if($user){
                $info['mp_lick'] = MpLick::where(['type_id'=>$info['id'],'user_id'=>$user['id']])->find() ? 1 : -1;
            }
        }
        $info['arrList'] = $arrList;
        MpTypeModer::where(['id'=>$id])->update(['visit_num'=>$info['visit_num']+1]);
        $this->success('操作成功',$info);
    }

	//获取背景色
	public function getBeiJing(){
		$id = $this->request->request('id','');
		$mp_id = $this->request->request('update_id','');
		if(!$id && $mp_id){
            $id = MpMp::where(['id'=>$mp_id,'status'=>1])->value('type_id');
		}
		$list = MpJson::where(['mp_type_id'=>$id])->select();
		foreach ($list as &$v) {
			$v['json_arr'] = json_decode($v['json'],true);
		}
		$this->success('操作成功',$list);
	}

	//发布产品
	public function addMp(){
        $data['company_logo'] = $this->request->request('company_logo','');
        $data['wx_img'] = $this->request->request('wx_img','');
        $data['serve_imgs'] = $this->request->request('serve_imgs','');
        $data['latitude'] = $this->request->request('latitude','');
        $data['longitude'] = $this->request->request('longitude','');
        $data['case_imgs'] = $this->request->request('case_imgs','');
        $data['username'] = $this->request->request('username','');
        $data['company'] = $this->request->request('company','');
        $data['position'] = $this->request->request('position','');
        $data['bj_img'] = $this->request->request('bj_img','');
        $data['phone'] = $this->request->request('phone','');
        $data['type_id'] = $this->request->request('id','');
        $data['mail'] = $this->request->request('mail','');
        $data['address'] = $this->request->request('address','');
        $data['introduce'] = $this->request->request('introduce','');
        $data['qy_introduce'] = $this->request->request('qy_introduce','');
        $data['dp_introduce'] = $this->request->request('dp_introduce','');
        $data['company_logo'] = $this->request->request('company_logo','');
        $data['mp_json_id'] = $this->request->request('mp_json_id','');
        $data['company_logo'] = $this->request->request('company_logo','');
        $data['order_id'] = $this->request->request('order_id','');
        $data['module_json'] = $this->request->request('module_json','');
		$data['avatar'] = $this->user['avatar'];
		$data['module_json_id'] = $this->request->request('module_json_id','');
        $data['module_json_name'] = $this->request->request('module_json_name','');
        $data['module_json_type'] = $this->request->request('module_json_type','');
        $data['module_json_status'] = $this->request->request('module_json_status','');
        $data['module_json_zdy_title'] = $this->request->request('module_json_zdy_title','');
        $data['module_json_text'] = $this->request->request('module_json_text','');
        $data['module_json_text_json'] = $this->request->request('module_json_text_json','');
		
        $type_info = MpTypeModer::where(['id'=>$data['type_id']])->find();


		$id =  $this->request->request('id','');
		$update_id =  $this->request->request('update_id','');
		if(!$update_id && $this->user['use_num'] < 1 && $type_info['price'] > 0 ){
			$this->error('参数错误,请联系客服');    
		}
		if(!$data['username']){
            $this->error('姓名不可为空');
        }
		if(empty($data['phone']) || !check_phone($data['phone'])){
            $this->error('请输入有效的手机号码');
		}
		if(!$data['mail']){
            $this->error('邮箱不可为空');
        }
		if(!$data['address']){
            $this->error('地址不可为空');
        }
		//编辑
		if($update_id){
			$id = $update_id;
			MpMp::where(['id'=>$id])->update($data);
		}else{
			$data['user_id'] = $this->user['id'];
			$data['add_time'] = time();
			$data['type'] = $type_info['type'];
			$id = MpMp::insertGetId($data);
			UserOrder::where(['id'=>$data['order_id']])->update(['status'=>3]);
		}
        $data['id'] = $id;
        $this->get_yl_img($data);
        
        if(!$id){
            $this->error('操作错误');
        }else{
            if(!$update_id && $type_info['price'] > 0){
                //创建成功可用次数减一
                User::where(['id'=>$this->user['id']])->update(['use_num'=>$this->user['use_num']-1]);
            }

			$this->success('操作成功',['id'=>$id,'use_num'=>$this->user['use_num']-1]);
		}
    }

    //生成预览图
    public function check_img()
    {
        $data['username'] = $this->request->request('username','');
        $data['position'] = $this->request->request('position','');
        $data['phone'] = $this->request->request('phone','');
        $data['type_id'] = $this->request->request('id','');
        $data['mail'] = $this->request->request('mail','');
        $data['address'] = $this->request->request('address','');
        $data['company'] = $this->request->request('company','');
        $data['mp_json_id'] = $this->request->request('mp_json_id','');

        $mp_json = MpJson::where(['id'=>$data['mp_json_id']])->find();

        $json = json_decode($mp_json['json'],true);
        for ($k = 0; $k < count($json['content']); $k++) {
            if($json['title'][$k] == '姓名' && !$data['username']){
                $this->error('姓名不可为空');
            }elseif($json['title'][$k] == '岗位' && !$data['position']){
                $this->error('岗位不可为空');
            }elseif($json['title'][$k] == '邮箱' && !$data['mail']){
                $this->error('邮箱不可为空');
            }elseif($json['title'][$k] == '电话' && !$data['phone']){
                $this->error('电话不可为空');
            }elseif($json['title'][$k] == '公司' && !$data['company']){
                $this->error('公司不可为空');
            }elseif($json['title'][$k] == '地址' && !$data['address']){
                $this->error('地址不可为空');
            }
        }
        $img = $this->get_yl_img($data,1);
		$this->success('操作成功',$img);
    }

    //生成预览图
    public function get_yl_img($data,$status = 0)
    {
        $mp_json = MpJson::where(['id'=>$data['mp_json_id']])->find();
        $bg = $mp_json['beijing_img'];
        if(strpos($bg, 'cn/') !== false){
            $bgArr = explode('cn/',$bg);
        }else{
            $bgArr = explode('com/',$bg);
        }
        $bg = $bgArr[1];
        $zt = ROOT_PATH.'public/assets/fonts/Alibaba-PuHuiTi-Regular.ttf';
        $img0 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img1 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img2 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img3 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img4 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img5 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img6 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img7 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img8 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $img9 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
        $json = json_decode($mp_json['json'],true);
        for ($k = 0; $k < count($json['content']); $k++) {
            if($json['title'][$k] == '姓名'){
                $json['content'][$k] = $data['username'];
            }elseif($json['title'][$k] == '岗位'){
                $json['content'][$k] = $data['position'];
            }elseif($json['title'][$k] == '邮箱'){
                $json['content'][$k] = $data['mail'];
            }elseif($json['title'][$k] == '电话'){
                $json['content'][$k] = $data['phone'];
            }elseif($json['title'][$k] == '公司'){
                $json['content'][$k] = $data['company'];
            }elseif($json['title'][$k] == '地址'){
                $json['content'][$k] = $data['address'];
            }
        }

        for ($k = 0; $k < count($json['content']); $k++) {
            if($k == 0){
                $image0 = \think\Image::open($bg);
                $image0->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img0);
            }elseif($k == 1){
                $image1 = \think\Image::open($img0);
                $image1->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img1);
            }elseif($k == 2){
                $image2 = \think\Image::open($img1);
                $image2->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img2);
            }elseif($k == 3){
                $image3 = \think\Image::open($img2);
                $image3->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img3);
            }elseif($k == 4){
                $image4 = \think\Image::open($img3);
                $image4->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img4);
            }elseif($k == 5){
                $image5 = \think\Image::open($img4);
                $image5->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img5);
            }elseif($k == 6){
                $image6 = \think\Image::open($img5);
                $image6->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img6);
            }elseif($k == 7){
                $image7 = \think\Image::open($img6);
                $image7->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img7);
            }elseif($k == 8){
                $image8 = \think\Image::open($img7);
                $image8->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img8);
            }elseif($k == 9){
                $image9 = \think\Image::open($img8);
                $image9->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img9);
            }
        }
        $count = count($json['content']);
        if($count == 1){
            $res = $img0;
        }if($count == 2){
            unlink($img0);
            $res = $img1;
        }if($count == 3){
            unlink($img0);
            unlink($img1);
            $res = $img2;
        }if($count == 4){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            $res = $img3;
        }if($count == 5){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            $res = $img4;
        }if($count == 6){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            unlink($img4);
            $res = $img5;
        }if($count == 7){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            unlink($img4);
            unlink($img5);
            $res = $img6;
        }if($count == 8){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            unlink($img4);
            unlink($img5);
            unlink($img6);
            $res = $img7;
        }if($count == 9){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            unlink($img4);
            unlink($img5);
            unlink($img6);
            unlink($img7);
            $res = $img8;
        }if($count == 10){
            unlink($img0);
            unlink($img1);
            unlink($img2);
            unlink($img3);
            unlink($img4);
            unlink($img5);
            unlink($img6);
            unlink($img7);
            unlink($img8);
            $res = $img9;
        }
        $filePath = '/www/wwwroot/mingpian/public/'.$res;
        $IndexOssModel = new IndexOssModel();

        $url = $IndexOssModel->bendi_upload($filePath);
        unlink($res);
        
        if($status == 1){
            return $url;
        }else{
            $arr = [
                'mp_id'=>$data['id'],
                'json'=>json_encode($json),
                'add_time'=>time(),
                'beijing_img'=>$mp_json['beijing_img'],
                'preview_img'=>$url
            ];
            MpJson::insert($arr);
        }

        
    }

}